<script>
	import {
		HTTP_IMG_UTL
	} from "@/config/app"
	import {
		UniWebsocket
	} from "@/utils/uni-websocket";
	import store from '@/store/index.js';
	import {
		EventBus
	} from '@/common/event-bus.js';
	// #ifdef WEB
	import {
		init,
		login
	} from '@/utils/im'
	init();
	// #endif

	// #ifdef APP-PLUS
	import {
		init,
		login
	} from '@/utils/im'

	// 引入 华为小米 审核 弹窗组件
	import {
		registerRequestPermissionTipsListener,
		unregisterRequestPermissionTipsListener,
		setRequestPermissionTips
	} from "@/uni_modules/uni-registerRequestPermissionTips"
	var PermissionTips = {
		"android.permission.CAMERA": "<h4 style=\"font-size:40px;\">GLUZ对相机/摄像头权限申请说明</h4><font color=#cccccc>便于您使用该功能拍照上传您的照片/视频及用于更换头像、意见反馈、保存相册、发布商品/动态、下载与客服沟通等场景中使用</font>",
		//"android.permission.READ_PHONE_STATE": "<h4 style=\"font-size:40px;\">正在读取网络状态权限</h4><font color=#cccccc>通讯录权限不会获取任何信息，请注意通讯录权限不会获取任何信息，请注意通讯录权限不会获取任何信息，请注意</font>",
		"android.permission.WRITE_EXTERNAL_STORAGE": "<h4 style=\"font-size:40px;\">GLUZ对存储空间/照片权限申请说明</h4><font color=#cccccc>便于您使用该功能上传您的照片/图片/视频及用于更换头像、意见反馈、保存相册、发布商品/分享、下载与客服沟通等场景中读取和写入相册和文件内容。</font>",
		"android.permission.RECORD_AUDIO": "<h4 style=\"font-size:40px;\">GLUZ对录音功能申请说明</h4><font color=#cccccc>当您使用聊天发送语音消息或音频聊天时，GLUZ需要使用您的麦克风</font>",
		//"android.permission.READ_EXTERNAL_STORAGE": "<h4 style=\"font-size:40px;\">GLUZ对存储空间/照片权限申请说明</h4><font color=#cccccc>便于您使用该功能上传您的照片/图片/视频及用于更换头像、意见反馈、保存相册、发布商品/分享、下载与客服沟通等场景中读取和写入相册和文件内容。</font>",
	}

	// 旧版的推送（作废）
	// import TIMPushConfigs from "./timpush-configs.json";
	// const TIMPush = uni.requireNativePlugin("TencentCloud-TIMPush");
	// console.warn(`TencentCloud-TIMPush: uni.requireNativePlugin ${!!TIMPush ? 'success' : 'fail'}`);
	// uni.$TIMPush = TIMPush;
	// uni.$TIMPushConfigs = TIMPushConfigs || {};

	// if (uni.$TIMPush) {
	// 	uni.$TIMPush.setOfflinePushListener((data) => {
	// 		// 透传 entity 中的内容，不包含推送的 Message
	// 		console.log('setOfflinePushListener', data);
	// 	});
	// }
	// 旧版的推送（作废）


	// 新版的 集成 TencentCloud-Push  只有hbuilderX 4.24好使
	import * as Push from '@/uni_modules/TencentCloud-Push';
	const SDKAppID = 1400818966; // 您的 SDKAppID
	const appKey = '5pHuHI6yPdrnl481F7OfIHzWi8Uop6qMYgfDOvZ4XTeSRFtcFVUm0B4rIEusroyo'; // 客户端密钥
	try{
		Push.registerPush(SDKAppID, appKey, (data) => {
			console.log('registerPush ok', data);
			Push.getRegistrationID((registrationID) => {
				console.log('getRegistrationID ok', registrationID);
			});
		}, (errCode, errMsg) => {
			console.error('registerPush failed', errCode, errMsg);
		});
		
		// 监听在线推送 // res 为消息内容
		Push.addPushListener(Push.EVENT.MESSAGE_RECEIVED, (res) => {
			console.log('message received', res);
		});
		
		// 监听在线推送被撤回 // res 为被撤回的消息 ID
		Push.addPushListener(Push.EVENT.MESSAGE_REVOKED, (res) => {
			console.log('message revoked', res);
		});
		
	}catch(e){
		console.log(e)
	}



	// 请按照 $TUICallKit 命名并且通过 uni.$TUICallKit 全局引入，修改命名会出现不生效的情况   人工客服
	uni.$TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
	console.log(uni.$TUICallKit, "TUICallKit ｜ ok"); // 本地日志 


	//	init();
	// #endif


	export default {
		name: 'app',
		globalData: {
			site: {}, //全局变量
			lang: '', //全局语言
			im: { //全局IM状态
				type: "list",
				mobile: "",
				to_mobile: ""
			},
			version: '2.6.5',	//版本号
			yuyin: false,		//IM 录音按钮是否显示
			agreeApp: false,		// 全局同意协议
			chat_report: false,		// IM 进入前是否显示 权限授权弹窗
			chat_report2: false,	// IM 里面是否显示 权限授权弹窗
			
			websocketStatus: false,		// socket 连接状态
			websocket: null,			// socket data
			
			activity: 0				// 首页供应商 发布赠送会员 弹窗标志位

		},
		onLaunch: function() {
			const that = this;
			
		
			
			
			//动态设置标题
			uni.addInterceptor("navigateTo", {
				invoke(e) {
					try {
						if (e.url.indexOf("title") > -1) {
							const paramsStr = e.url.split("?")[1];
							if (paramsStr) {
								const params = paramsStr.split("&");
								const titleStr = params.find(item => item.indexOf("title") > -1)
								const title = titleStr.split("=")[1]
								if (title) {
									that.log(title)
									setTimeout(() => {
										uni.setNavigationBarTitle({
											title: that.$t(title)
										})
									}, 100)
								}
							}
						} else {
							const pages = {
								// "/pages/index/freightForwarder/freightForwarder?type=1": `${that.$t("跨境货代")}-${that.$t("推广")}`,
								// "/pages/index/freightForwarder/freightForwarder?type=2": `${that.$t("跨境货代")}-${that.$t("竞标")}`,
							}
							that.log(e.url)
							if (pages[e.url]) {
								that.log(pages[e.url])
								setTimeout(() => {
									uni.setNavigationBarTitle({
										title: pages[e.url]
									})
								}, 100)
							}
						}
					} catch (e) {
						console.log(e);
					}
				}
			})


			//引入全局变量
			that.$u.api.basic.getSite().then(res => {
				that.globalData.site = res
				that.globalData.yuyin = res.yuyin
				that.globalData.chat_report = res.chat_report
				that.globalData.chat_report2 = res.chat_report2

				//语音功能是否开启
				that.$u.api.basic.getContentData({
					type: "按住说话",
				}).then(re => {
					that.globalData.yuyin = re.content

					console.log(that.globalData.yuyin)

					// 引入 华为小米 审核 弹窗组件
					// #ifdef APP-PLUS
					if (that.globalData.yuyin == '0') {
						var brand = uni.getSystemInfoSync().deviceBrand
						setRequestPermissionTips(PermissionTips)
						registerRequestPermissionTipsListener({
							onRequest: (e) => {
								console.log(e)
							},
							onConfirm: (e) => {
								console.log(e)
							},
							onComplete: (e) => {
								console.log(e)
								// 华为手机在权限禁止之后，再次申请权限不会出现权限申请框。此时应该引导用户去系统设置开启此权限，不应该频繁申请。
								//if (brand.toLowerCase() == "huawei") {
								var tips = {}
								var hasDeniedPermission = false
								for (var k in PermissionTips) {
									if (e[k] != "denied") {
										tips[k] = PermissionTips[k]
									} else {
										hasDeniedPermission = true
									}
								}
								setRequestPermissionTips(
									tips) // 更新弹框提醒，防止华为手机不出现权限申请框时权限提醒框闪烁的情况
								// if (hasDeniedPermission)
								// 	uni.showModal({
								// 		content: "权限已经被拒绝，请前往设置中开启"
								// 	})
								//}
							}
						})
					}
					// #endif
					// 引入 华为小米 审核 弹窗组件


				})






				that.$isResolve();
			})

			//全局语言
			const lang = uni.getStorageSync('lang')
			that.$i18n.locale = lang
			that.globalData.lang = lang

			//全局登录手机号  并且连接websocket
			const mobile = uni.getStorageSync('mobile')
			if (mobile) {
				that.connect_workman(mobile)
			}

			//全局平台
			let plat = uni.getStorageSync('plat')
			if (!plat) {
				uni.getSystemInfo({
					success: function(res) {
						if (res.uniPlatform === 'app') {
							plat = 'app'
						} else if (res.uniPlatform === 'web') {
							plat = 'web'
						} else if (res.uniPlatform === 'mp-weixin') {
							plat = 'mp-weixin'
						}
						uni.setStorage({
							key: 'plat',
							data: plat
						})
					}
				})
			}

			//全局版本
			uni.setStorage({
				key: 'version',
				data: that.globalData.version
			})

			console.log("当前语言：", lang, "当前用户：", mobile, "当前环境：", plat)


			// TUICore login
			// #ifdef APP-PLUS
			if (mobile) {
				login()
			}
			// 在 App.vue, 生命钩子 onLaunch 中监听
			// TIMPush.setOfflinePushListener((data) => {
			// 	// 透传 entity 中的内容，不包含推送的 Message
			// 	console.log('setOfflinePushListener', data);
			// 	// 跳转到应用内指定界面
			// 	uni.navigateTo({
			// 		url: "/pages/tabbar/message/index",
			// 	});
			// });

			//plus.push.addEventListener("click", (message)=>{
			//console.log(message)
			// let { url } = message.payload;
			// if(url){
			// 	uni.navigateTo({
			// 		url,
			// 		success: () => {}, // 可以根据需求删除消息 this.remove(message);
			// 		complete: () => {} // 可以根据需求删除消息 this.remove(message);
			// 	});
			// }
			//})

			//plus.push.addEventListener( "receive", function( msg ) {
			// console.log(msg)
			// uni.showToast({
			// 	title: msg.content,
			// 	icon: "none",
			// 	position: 'top',
			// 	duration:3000
			// });
			//})
			// #endif

			// WEB login
			// #ifdef WEB
			if (mobile) {
				login()
			}
			// #endif

		},

		onShow: function() {
			var that = this
			const mobile = uni.getStorageSync('mobile')
			if (mobile) {
				that.connect_workman(mobile)
			}
			// #ifdef APP-PLUS
			Push.getNotificationExtInfo((extInfo) => {
				//console.log('这个是IM 聊天的推送');
			})

			this.getList();
			// #endif 

			//设置tabbar文字
			this.$store.commit("setTabBar", this)
			this.setTabBarLanguage();

			// #ifdef APP-PLUS
			let args = plus.runtime.arguments;
			let arr = args.match(/gluzshop/i);
			if (!!arr) {
				this.globalData.isJump = true;
			}
			console.log("args==========", args)
			if (args && arr && this.globalData.isJump) {
				const bid = this.getUrlParam("bid", args);
				const type = this.getUrlParam("type", args);
				this.globalData.isJump = false;
				uni.navigateTo({
					url: `/pages/shopping/index/index?bid=${bid}&type=${type}`
				})
				plus.runtime.arguments = null;
				plus.runtime.arguments = "";
			}
			// #endif
		},
		onHide: function() {
			// #ifdef APP-PLUS
			this.getList();
			// #endif 
		},
		onUnload() {
			unregisterRequestPermissionTipsListener(null)
		},
		onExit: function() {
			unregisterRequestPermissionTipsListener(null)
		},
		methods: {
			// 通过调用 uni.setTabBarItem 方法来动态设置 TabBar 的文本
			setTabBarLanguage() {
				const tabBarList = [{
						text: this.$t('首页')
					},
					{
						text: this.$t('工作台')
					},
					{
						text: this.$t('发布')
					},
					{
						text: this.$t('消息')
					},
					{
						text: this.$t('我的')
					}
				];
				tabBarList.forEach((item, index) => {
					uni.setTabBarItem({
						index: index,
						text: item.text
					});
				});
			},
			//获取未读的角标
			getList() {
				const mobile = uni.getStorageSync('mobile') || false
				var that = this
				//是否在登入状态（看自己代码检测登入状态的判断方式）
				if (uni.getStorageSync('mobile') && mobile) {
					that.$u.api.message.getC2cUnreadMsgNum({
						mobile: mobile,
					}).then(res => {
						that.$u.api.basic.getNoticeNum().then(r => {
							var num = Number(r.other) + Number(r.system) + Number(uni.getStorageSync(
								"onTotalUnreadMessageCountUpdated"))
							if (num > 0) {
								this.setBadge(num)
							} else {
								this.clearBadge()
							}
						})
					}).catch(error => {
						this.clearBadge()
					})
				} else {
					//未登入状态清空
					this.clearBadge()
				}
			},
			//设置角标
			setBadge(num) {
				plus.runtime.setBadgeNumber(num)
			},
			//清除角标
			clearBadge() {
				plus.runtime.setBadgeNumber(-1)
			},
			//连接workman
			connect_workman(mobile) {
				let that = this;
				var connect_dev = mobile;

				if (connect_dev !== undefined) {
					if (!that.globalData.websocketStatus) {
						const websocket1 = new UniWebsocket({
							url: 'ws://39.104.74.83:9003',
						});
						console.log(websocket1)
						websocket1.connect({
							connectSuccCallback: function(res) {
								that.globalData.websocketStatus = true;
								that.globalData.websocket = websocket1;
								console.log('开启连接')
							},
							connectErrorCallback: function(res) {
								console.log('连接失败')
							},
							openCallback: function(res) {
								websocket1.send({
									dev: connect_dev
								});
							},
							messageCallback: async function(res) {
								console.log('msg', res)
								store.commit("getC2cUnreadMsgNum")
								const notificationItem = JSON.parse(res.data);
								notificationItem.show = false;
								if (notificationItem.table_type == 100) {
									notificationItem.countdown = ''
									notificationItem.intervalId = null
									notificationItem.countdownshow = false
								}
								notificationItem.id = new Date().getTime() + Math.floor(Math.random() * 1000);
								console.log('msg1111', notificationItem)
								store.commit('setSocketState', notificationItem)
								store.commit("getMyWorkMessage")
								store.commit("setWorkRefresh")
							}
						});
					}
				}
			},
		}


	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
	/*每个页面公共css */
	@import "@/common/main.scss";

	uni-page-body {
		height: 100%;

	}

	uni-tabbar {
		z-index: 9999 !important;
	}
</style>